import { Body, Controller, Get, Post, Query, Req, UseGuards } from '@nestjs/common';
import { RemoveDataService as removeDataService } from './services/remove-data.service';
import { StageService } from '../stage/stage.service';
import { ApiBearerAuth, ApiBody, ApiOperation } from '@nestjs/swagger';
import { Auth } from 'src/common/decorators/auth.decorator';
import { RequirePermission } from 'src/common/decorators/permission.decorator';
import { TournamentService } from '../tournament/tournament.service';
import { CopyDataDto } from './dto/copy-data.dto';
import { CopyDataService } from './services/copy-data.service';
import { TournamentCacheService } from '../tournament/tournament.cache.service';

@Auth()
@ApiBearerAuth()
@Controller('common')
export class CommonController {
  constructor(
    private readonly removeDataService: removeDataService,
    private readonly stageService: StageService,
    private readonly tournamentService: TournamentService,
    private readonly copyDataService: CopyDataService,
    private readonly tournamentCacheService: TournamentCacheService,
  ) {}

  @RequirePermission('1003004')
  @Get('deleteStage')
  async deleteStage(@Query('id') id: string) {
    const stageDetail = await this.stageService.getStageDetail(+id);
    await this.removeDataService.deleteStageDataWithTransaction([stageDetail]);
    await this.tournamentCacheService.handleTournamentUpdate({
      id: stageDetail.tournamentId,
    });
  }

  @RequirePermission('1001004')
  @Get('deleteTournament')
  async deleteTournament(@Query('id') id: string) {
    // const tournamentDetail =
    //   await this.tournamentService.findTournamentDetail(+id);
    // return this.removeDataService.deleteTournamentData([tournamentDetail]);
    const stageList = await this.stageService.listByTournamentIdForDelete(+id);
    if (stageList && stageList.length) {
      await this.removeDataService.deleteStageDataWithTransaction(stageList);
    }
    const tournamentDetail =
      await this.tournamentService.findTournamentForDelete(+id);
    if (tournamentDetail) {
      await this.removeDataService.deleteTournamentDataWithTransaction([
        tournamentDetail,
      ]);
    }
  }

  @ApiOperation({
    summary: '复制赛事',
    description: '根据现有赛事ID复制创建新赛事',
  })
  @ApiBody({ type: CopyDataDto, description: '复制赛事的请求参数' })
  @RequirePermission('1001002')
  @Post('copy')
  async copyTournament(@Req() request, @Body() copyTournamentDto: CopyDataDto) {
    const user = request.user;
    copyTournamentDto.type = copyTournamentDto.type;
    copyTournamentDto.user = user;
    return await this.copyDataService.copyTournament(copyTournamentDto);
  }
}
